package com.dranie.action;

import com.dranie.entity.Category;
import com.dranie.interceptor.CategoryInterceptor;
import com.dranie.validator.CategoryValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

import java.util.List;

/**
 * BlogController
 * 注意：在实际项目中业务与sql需要写在Model中，此demo仅为示意,故将sql写在了Controller中
 */
@Before(CategoryInterceptor.class)
public class CategoryController extends Controller {

    public void index() {
        setAttr("categoryPage", Category.dao.paginate(getParaToInt(0, 1), 10, "select c.*,p.name pname", " from category c left join category p on c.parent=p.id  order by c.id asc"));
        render("list.html");
    }

    public void child() {
        Integer parent = getParaToInt();
        List<Category> categorys = Category.dao.find("select id,name from category where parent = ? order by name", parent);
        setAttr("categorys", categorys);
        renderJson();
    }

    public void add() {
        setAttr("parents", Category.dao.find("select * from category where parent is null order by id asc"));
    }

    @Before(CategoryValidator.class)
    public void save() {
        getModel(Category.class).save();
        redirect("/admin/category");
    }

    public void edit() {
        setAttr("parents", Category.dao.find("select * from category where parent is null order by id asc"));
        setAttr("category", Category.dao.findById(getParaToInt()));
    }

    @Before(CategoryValidator.class)
    public void update() {
        getModel(Category.class).update();
        redirect("/admin/category");
    }

    public void delete() {
        Category.dao.deleteById(getParaToInt());
        redirect("/admin/category");
    }
}


